package com.qiantu.phone.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLDeviceGroupDBManager;
import com.qiantu.api.entity.DeviceBaseConfigInfo;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceBindGroupBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.ui.activity.PanelBindDeviceActivity;
import com.qiantu.phone.ui.activity.PanelBingingActivity;
import com.qiantu.phone.ui.adapter.DeviceFilterItemAdapter;
import com.qiantu.phone.ui.adapter.ManagerDeviceAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class DeviceListFragment extends AppFragment<AppActivity> {
    private RecyclerView deviceList;
    private ManagerDeviceAdapter deviceAdapter;

    private PanelBingingActivity mActivity;
    private AppActivity appActivity;
//    设备选择类型： 0：拍照绑定；1：弗雷克设备过滤;2:开关批量绑定;3:温控面板绑定设备
    private int selectType;
    private String selectKey;
    private Map<String,Integer> selectData;

    public DeviceListFragment() {
    }

    public static DeviceListFragment newInstance(PanelBingingActivity activity,int selectType) {
        DeviceListFragment fragment = new DeviceListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        fragment.mActivity = activity;
        fragment.selectType = selectType;
        return fragment;
    }

    public static DeviceListFragment newInstance(AppActivity activity,int selectType,String selectKey) {
        DeviceListFragment fragment = new DeviceListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        fragment.appActivity = activity;
        fragment.selectType = selectType;
        fragment.selectKey = selectKey;
        return fragment;
    }

    public static DeviceListFragment newInstance() {
        DeviceListFragment fragment = new DeviceListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {}
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_scene_list;
    }

    @Override
    protected void initView() {
        deviceList = findViewById(R.id.scene_list);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        deviceList.setLayoutManager(gridLayoutManager);
        deviceAdapter = new ManagerDeviceAdapter(getContext(),selectType);
        deviceAdapter.setIsDeviceAction(true);
        deviceList.setAdapter(deviceAdapter);
        deviceAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                DeviceBean device = deviceAdapter.getData().get(position);
                if(selectType == 3){
                    PanelBindDeviceActivity activity = (PanelBindDeviceActivity) appActivity;
                    activity.addDevice(device);
                }else {
                    mActivity.showDeviceOperateView(device);
                }
            }
        });
        deviceAdapter.setOnChildClickListener(R.id.btn_sort_device_action,new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                if(selectType == 3){
                    DeviceBean device = deviceAdapter.getData().get(position);
                    PanelBindDeviceActivity activity = (PanelBindDeviceActivity) appActivity;
                    activity.removeData(device.getDeviceSerialNo());
                }else{
                    mActivity.removeBingingData(deviceAdapter.getItem(position).getDeviceSerialNo(),1);
                }
                deviceAdapter.getItem(position).setTemporary(null);
                deviceAdapter.notifyItemChanged(position);
            }
        });
    }
    @Override
    protected void initData() {
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
                    @Override
                    public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                        List<DeviceBean> deviceBeans;
                        if(selectType == 3){
                            deviceBeans = LLDeviceDBManager.getInstance(getContext()).getDeviceByMainType(selectKey,false,null,false);
                        }else{
                            deviceBeans = LLDeviceDBManager.getInstance(getContext()).getAll(false,null,false);
                        }

                        Log.d("sqlite_debug", "end");
                        emitter.onNext(deviceBeans);
                    }
                }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        List<DeviceBean> newDeviceBeans = new ArrayList<>();
                        if(selectType == 0 || selectType == 2){
                            for(DeviceBean deviceBean : devices){
                                DeviceBaseConfigInfo deviceBaseConfigInfo = DeviceInfoParseUtil.parseData(getContext(), deviceBean.getDeviceType(), DeviceBaseConfigInfo.class);
                                if(deviceBaseConfigInfo.getBingingData().size() != 0 || deviceBean.getType().equals("universal") || deviceBean.getDeviceType().equals("universal_freshair")){
                                    newDeviceBeans.add(deviceBean);
                                }
                            }
                        }else if(selectType == 1){
                            for(DeviceBean deviceBean : devices){
                                if(deviceBean.getDeviceType().equals("tctdl") || deviceBean.getDeviceType().equals("adjustLight") || deviceBean.getType().equals("curtain")){
                                    newDeviceBeans.add(deviceBean);
                                }
                            }
                        }else{
                            newDeviceBeans = devices;
                        }
                        for(DeviceBean bean : newDeviceBeans){
                            if(selectData != null && selectData.get(bean.getDeviceSerialNo()) != null){
                                bean.setTemporary(selectData.get(bean.getDeviceSerialNo()));
                            }
                        }
                        devices = newDeviceBeans;
                        deviceAdapter.setTotalData(devices);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }
    @Override
    public void onResume() {
        super.onResume();
        //没获取到数据才再刷新
//        if(deviceAdapter.getData() == null || deviceAdapter.getData().size() == 0){
//            initData();
//        }
    }

    private boolean isSingleSelect = false;
    public void setSingleSelect(boolean value) {
        isSingleSelect = value;
    }

    public void setTotalData(List<DeviceBean> data){
        deviceAdapter.setTotalData(data);
    }

    public void setSortData(String deviceSerialNo,int index){
        for(DeviceBean deviceBean : deviceAdapter.getData()){
            if(deviceBean.getDeviceSerialNo().equals(deviceSerialNo)){
                deviceBean.setTemporary(""+index);
                deviceAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    public void setSelectData(Map<String,Integer> selectData){
        this.selectData = selectData;
    }
}
